package com.seashop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seashop.entity.MemberRelation;
import com.seashop.entity.MemberUpgradeLog;
import com.seashop.enums.VipStatusEnum;
import com.seashop.mapper.MemberRelationMapper;
import com.seashop.mapper.MemberUpgradeLogMapper;
import com.seashop.service.IMemberRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author moredln
 * @since 2020-11-22
 */
@Service
public class MemberRelationServiceImpl extends ServiceImpl<MemberRelationMapper, MemberRelation> implements IMemberRelationService {

    @Autowired
    private MemberRelationMapper memberRelationMapper;
    @Autowired
    private MemberUpgradeLogMapper memberUpgradeLogMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MemberRelation memberDegrade(int userId, int newLevel) {
        MemberRelation memberRelation = memberRelationMapper.selectById(userId);

        if (memberRelation.getVipStatus() == VipStatusEnum.VIP_TRIAL_ING.ordinal()) {
            memberRelation.setVipStatus(VipStatusEnum.VIP_TRIAL_EXPIRE.ordinal());
        } else if (memberRelation.getVipStatus() == VipStatusEnum.VIP_PAID.ordinal()) {
            memberRelation.setVipStatus(VipStatusEnum.VIP_PAID_EXPIRE.ordinal());
        }

        memberRelation.setUserLevel(newLevel);
        memberRelation.setUpdateTime(LocalDateTime.now());
        memberRelationMapper.insert(memberRelation);

        // upgrade log
        MemberUpgradeLog memberUpgradeLog = memberUpgradeLogMapper.selectOne(new QueryWrapper<MemberUpgradeLog>().eq("user_id",userId));
        if (memberUpgradeLog != null) {
            memberUpgradeLogMapper.delete(new QueryWrapper<MemberUpgradeLog>().eq("user_id",userId));
        }

        return memberRelation;
    }

}
